package com.example.handler;

import com.example.constant.MqConstants;
import com.example.dto.UserCouponDTO;
import com.example.entity.Coupon;
import com.example.service.CouponService;
import com.example.service.UserCouponService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author circle48
 */
@RequiredArgsConstructor
@Slf4j
@Component
public class PromotionMqHandler {

    @Resource
    private UserCouponService userCouponService;

    @Resource
    private CouponService couponService;

    @RabbitListener(
            bindings = @QueueBinding(
                    exchange = @Exchange(name = MqConstants.Exchange.PROMOTION_TOPIC,type = ExchangeTypes.TOPIC),
                    value = @Queue(name = "coupon.receive.queue",durable = "true"),
                    key = MqConstants.Key.COUPON_RECEIVE
            )
    )
    public void listenCouponReceiveMessage(UserCouponDTO dto){
        //1.判断
        if(dto == null){
            log.error("消息数据为null");
            return;
        }
        //2.调用业务
        Coupon coupon = couponService.getById(dto.getCouponId());
        if(coupon == null){
            throw new RuntimeException("优惠券不存在");
        }
        userCouponService.checkAndCreateUserCoupon(coupon,dto.getUserId());

    }
}